package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.TaoHuaSound;
import com.tanhua.domain.vo.TaoHuaSoundVO;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.TaoHuaSoundApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TaoHuaSoundService {
    @Reference
    private TaoHuaSoundApi taoHuaSoundApi;

    // 注入fastdfs文件上传客户端对象
    @Autowired
    private FastFileStorageClient storageClient;

    // 注入web服务器对象, 主要用来获取上传地址
    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String RANDOM_KEY = "randomList";

    private final Integer SUM = 10;

    @Reference
    private UserInfoApi userInfoApi;


    /**
     * 发送语音
     * @param soundFile 语音文件
     */
    public ResponseEntity<Object> sendVoice(MultipartFile soundFile) throws IOException {
        InputStream input = soundFile.getInputStream();
        long size = soundFile.getSize();
        String sufix = soundFile.getOriginalFilename().substring(soundFile.getOriginalFilename().lastIndexOf(".") + 1);

        //上传文件到storage
        StorePath storePath = storageClient.uploadFile(input, size, sufix, null);
        String soundUrl = webServer.getWebServerUrl() + storePath.getFullPath();


        //存入mongodb
        TaoHuaSound taoHuaSound = new TaoHuaSound();
        taoHuaSound.setId(ObjectId.get());
        taoHuaSound.setSoundUrl(soundUrl);
        taoHuaSound.setUserId(UserHolder.getUserId());
        taoHuaSound.setState(0);
        taoHuaSoundApi.save(taoHuaSound);

        //将id存入redis方便随机获取语音
        String randomJsonStr = redisTemplate.opsForValue().get(RANDOM_KEY);
        List<String> randomList;
        if (randomJsonStr == null) {
            randomList = new ArrayList<>();
        } else {
            randomList = JSON.parseObject(randomJsonStr, List.class);
        }
        randomList.add(taoHuaSound.getId() + "_" + UserHolder.getUserId());
        randomJsonStr = JSON.toJSONString(randomList);
        redisTemplate.opsForValue().set(RANDOM_KEY, randomJsonStr);

        return ResponseEntity.ok(null);
    }

    /**
     * 接收语音
     * @return
     */
    public ResponseEntity<Object> acceptVoice() {
        //从redis查询当前时间年月日如果有这个key就是当天没有就是第二天或者是第一次接收语音
        String key = new SimpleDateFormat("yyy-MM-dd").format(new Date());
        String redisNum = redisTemplate.opsForValue().get(key);
        if (redisNum == null) {
            redisNum = SUM + "";
        } else {
            redisNum = (Integer.parseInt(redisNum) - 1) + "";
        }
        redisTemplate.opsForValue().set(key, redisNum);

        //当剩余次数大于0就封装vo返回
        TaoHuaSoundVO taoHuaSoundVO;
        if (Integer.parseInt(redisNum) > 0) {
            String taoHuaId = this.getRandomVoiceId(UserHolder.getUserId());
            TaoHuaSound taoHuaSound = taoHuaSoundApi.getVoice(taoHuaId);
            UserInfo userInfo = userInfoApi.findById(taoHuaSound.getUserId());
            taoHuaSoundVO = new TaoHuaSoundVO();
            BeanUtils.copyProperties(userInfo, taoHuaSoundVO);
            taoHuaSoundVO.setSoundUrl(taoHuaSound.getSoundUrl());
            taoHuaSoundVO.setRemainingTimes(Integer.parseInt(redisNum));
        } else {
            taoHuaSoundVO = new TaoHuaSoundVO();
            taoHuaSoundVO.setRemainingTimes(0);
            taoHuaSoundVO.setNickname("你完了");
            taoHuaSoundVO.setAge(0);
        }
        return ResponseEntity.ok(taoHuaSoundVO);
    }

    /**
     * 获取随机VoiceID
     * @param userId
     * @return
     */
    public String getRandomVoiceId(Long userId) {
        String randomStr = redisTemplate.opsForValue().get(RANDOM_KEY);
        List<String> list = JSON.parseObject(randomStr, List.class);
        List<String> randomList = list.stream().filter(s -> !userId.toString().equals(s.split("_")[1])).collect(Collectors.toList());

        Collections.shuffle(randomList);
        String taoHuaId = randomList.get(new Random().nextInt(randomList.size()));
        list.remove(taoHuaId);
        redisTemplate.opsForValue().set(RANDOM_KEY, JSON.toJSONString(list));
        return taoHuaId.split("_")[0];
    }
}
